<template>
<div>
  <div id="commoditymanager" v-if="jobId == 1 || jobId==2">

    <el-row type="flex" align="middle"  justify="center" class="row-bg" style="height: 70px">
      <el-form :model="check" :rules="rules" :inline="true"  ref="check" status-icon class="demo-form-inline" label-position="left" size="small">
        <el-form-item label="商品名称" prop="goodName">
          <el-input v-model="check.goodName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品编码" prop="goodCode">
          <el-input v-model="check.goodCode" placeholder="请输入产地"></el-input>
        </el-form-item>
        <el-form-item label="上架状态" prop="shelfStatus">
          <el-select v-model="check.shelfStatus" clearable  placeholder="请选择" @change="queryGood" @clear="queryGood">
            <el-option
                key="0"
                label="未上架"
                value="0">
            </el-option>
            <el-option
                key="1"
                label="已上架"
                value="1">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryGood">查询</el-button>
          <el-button type="primary" @click="doReset('check')">重置</el-button>
          <el-button type="warning" @click="addGoods">新增</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row v-if="deleteAndAddShelfVisable" type="flex" align="middle"  justify="start" class="row-bg">
        <el-button type="danger" icon="el-icon-delete" circle size="mini"  @click="doDeleteBranch"></el-button>
        <el-button type="primary" @click="doAddShelf" size="mini">上架</el-button>
        <el-button type="primary" @click="doDeleteShelf" size="mini">下架</el-button>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-dark">
          <el-table
              :data="pageGoodData.list"
              height="80vh"
              border
              :header-cell-style="{'text-align':'center'}"
              style="width: 100%"
              @selection-change="handleSelectionChange">
            <el-table-column
                type="selection"
                fixed="left"
                width="30">
            </el-table-column>
            <el-table-column
                prop="goodCode"
                label="商品编号"
                width="80">
            </el-table-column>
            <el-table-column
                label="商品主图"
                width="135">
              <template slot-scope="scope">
              <el-avatar shape="square" :size="100" fit="fill" :src="scope.row.goodImg" ></el-avatar>
              </template>
            </el-table-column>
            <el-table-column
                prop="goodName"
                label="商品名称"
                width="150">
            </el-table-column>
            <el-table-column
                prop="goodPrice"
                label="商品价格（元）"
                width="80">
            </el-table-column>
            <el-table-column
                prop="marketPrice"
                label="市场价格（元）"
                width="80">
            </el-table-column>
            <el-table-column
                prop="discount"
                label="优惠价格（元）"
                width="80">
            </el-table-column>
            <el-table-column
                prop="repertory"
                label="库存量"
                width="80">
            </el-table-column>
            <el-table-column
                prop="typeName"
                label="商品类型"
                width="90">
            </el-table-column>
            <el-table-column
                label="创建时间"
                width="180">
              <template slot-scope="scope">
                <i class="el-icon-time"></i>
                <span style="margin-left: 10px">{{ scope.row.createTime}}</span>
              </template>
            </el-table-column>
            <el-table-column
                label="上架状态"
                width="200" align="center">
              <template slot-scope="scope">
              <el-switch
                  v-model="scope.row.shelfStatus"
                  disabled
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="已上架"
                  inactive-text="未上架"
                  :inactive-value="0"
                  :active-value="1">
              </el-switch>
              </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                width="140px">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="修改 " placement="top-start">
                  <el-button type="primary"  icon="el-icon-edit" circle @click="doUpdate(scope.row)" ></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="删除 " placement="top-start">
                  <el-button type="danger"  icon="el-icon-delete" circle @click="doDelete(scope.row.id)" ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <!--    分页部分-->
    <el-row  id ="pagehelper" type="flex" justify="center" class="el-row">
      <el-col :span="24">
        <el-pagination
            background
            layout="prev,sizes, pager, next,total,jumper"
            :page-sizes="[1, 5, 10]"
            @next-click="nextPage"
            @prev-click="prevPage"
            @size-change="sizeChange"
            @current-change="currentPage"

            :page-size="pageGoodData.pageSize"
            :current-page="pageGoodData.pageNum"
            :total="pageGoodData.total"
            :page-count="pageGoodData.pages">
        </el-pagination>
      </el-col>
    </el-row>
    <!--    对话框 添加&修改-->
    <el-dialog :title="addAndUpdate.title" :visible.sync="addAndUpdateIsVisiable" :modal="false">
      <el-form :model="rowData">
        <el-form-item label="商品编号:" :label-width="formLabelWidth">
          <el-input v-model="rowData.goodCode" autocomplete="off" :readonly="isUpdate"></el-input>
        </el-form-item>
        <el-form-item label="商品名:" :label-width="formLabelWidth">
          <el-input v-model="rowData.goodName" autocomplete="off" :readonly="isUpdate"></el-input>
        </el-form-item>
        <el-form-item label="商品主图:" :label-width="formLabelWidth">
<!--          <el-input v-model="rowData.goodImg" autocomplete="off"></el-input>-->
          <el-upload
              class="avatar-uploader"
              action="/api/common/upload"
              :headers="{'jwt':jwt}"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="rowData.goodImg" :src="rowData.goodImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品原价:" :label-width="formLabelWidth">
          <el-input v-model="rowData.goodPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价格:" :label-width="formLabelWidth">
          <el-input v-model="rowData.marketPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="优惠价格:" :label-width="formLabelWidth">
          <el-input v-model="rowData.discount" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品类型:" :label-width="formLabelWidth">
          <el-select v-model="rowData.typeId" placeholder="请选择">
            <el-option
                v-for="item in goodType"
                :key="item.id"
                :label="item.typeName"
                :value="item.id">
            </el-option>
          </el-select>
<!--          <el-input v-model="" autocomplete="off"></el-input>-->
        </el-form-item>
        <el-form-item label="上架状态" :label-width="formLabelWidth">
          <el-switch
              v-model="rowData.shelfStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="已上架"
              inactive-text="未上架"
              :inactive-value="0"
              :active-value="1">
          </el-switch>
        </el-form-item>
        <el-form-item label="是否仅在积分商城出售" :label-width="formLabelWidth">
          <el-switch
              v-model="rowData.isPointGoods"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="是"
              inactive-text="否"
              :inactive-value="0"
              :active-value="1">
          </el-switch>
        </el-form-item>
        <el-form-item label="库存量" :label-width="formLabelWidth">
          <el-input-number v-model="rowData.repertory" :min="1" :max="9999"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="doQuit">取 消</el-button>
        <el-button type="primary" @click="addAndUpdatesave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
  <div  v-if="jobId==3">
    <h1>
      无权限*_*
    </h1>
  </div>

  </div>
</template>

<script>
export default {
  name: "commoditymanager",
  data(){
    return{
      jobId:'',
      jwt:'',
      //分页相关
      pageGoodData:{
        list:'',
        total:'',
        pageNum:1,
        pageSize:5,
        pages:''
      },
      //查询相关
      check:{
        goodName:'',
        goodCode:'',
        shelfStatus:''
      },
      rules:{
        goodName: [
          { message: '商品名称', trigger: 'blur' }
        ],
        goodCode: [
          {  message: '商品编号', trigger: 'blur' }
        ],
        shelfStatus: [
          {message: '请选择上架状态', trigger: 'change' }
        ]
      },
        goodType:'',
      rowData:{
        id:'', //商品id
        goodName:'',//商品名
        goodCode:'',// 商品编号
        goodImg:'', //商品图片
        goodPrice:'', //商品单价
        marketPrice:'', //市场价格
        discount:'', //优惠价格
        typeId:'',  //类型id
        createTime:'', //创建时间
        shelfStatus:0,//上架状态，
        isPointGoods:0,
        repertory:1
      },
      formLabelWidth: '120px',

      // 添加修改
      addAndUpdateIsVisiable:false,
      addAndUpdate:{
        title:''
      },
      isUpdate:true,
      // 多选
      multipleSelection: [],
      deleteAndAddShelfVisable:false

    }
  },
  methods:{
    queryGood(){
      //alert()
      let jwt=localStorage.getItem("jwt");
      var url = '/api/goods/goodslist?goodName=' + this.check.goodName + '&goodCode=' + this.check.goodCode + '&shelfStatus=' + this.check.shelfStatus + '&pageNum=' + this.pageGoodData.pageNum + '&pageSize=' + this.pageGoodData.pageSize;
      this.$axios.get(url,{headers:{"jwt":jwt}})
          .then(response =>{
            // console.log(response.data);
            if(response.data.code==200){
              this.pageGoodData=response.data.data;
              // this.$message.success(response.data.msg);
            }else if(response.data.data==406) {
              this.$message.warning(response.data.msg);
              this.$router.push("/login")
            }else {
              this.pageGoodData.list=null;
              this.pageGoodData.pages=0;
              this.pageGoodData.total=0;
              this.pageGoodData.pageNum=1;
              this.pageGoodData.pageSize=5;
              this.$message.warning(response.data.msg);
            }
          });
    },
    doReset(check){
      this.$refs[check].resetFields();
      this.pageGoodData.pageSize=5;
      this.pageGoodData.pageNum=1;
      this.queryGood();
    },
    doDelete(id){
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let jwt=localStorage.getItem("jwt");
        let url="/api//goods/goodDelete?id="+id
        this.$axios
            .get(url,{headers:{'jwt':jwt}})
            .then(response =>{
            if(response.data.code==200){
              this.$message.success("删除成功");
            }else if(response.data.data==406) {
              this.$message.warning(response.data.msg);
              this.$router.push("/login")
            }else {
              this.$message.error("删除失败");
            }
            this.queryGood();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    doUpdate(rowData){
      this.addAndUpdate.title="修改商品信息"
      let row = JSON.parse(JSON.stringify(rowData));
      this.rowData.id=row.id;
      this.rowData.goodName=row.goodName;//商品名
      this.rowData.goodCode=row.goodCode;// 商品编号
      this.rowData.goodImg=row.goodImg; //商品图片
      this.rowData.goodPrice=row.goodPrice //商品单价
      this.rowData.marketPrice=row.marketPrice //市场价格
      this.rowData.discount=row.discount //优惠价格
      this.rowData.typeId= row.typeId //类型id
      this.rowData.createTime= row.createTime//创建时间
      this.rowData.shelfStatus=row.shelfStatus//上架状态
      this.rowData.isPointGoods=row.isPointGoods;
      this.rowData.repertory=row.repertory;
      this.isUpdate=true;
      this.addAndUpdateIsVisiable=true;
    },
    handleSelectionChange(val){
      this.multipleSelection=val;
      if(this.multipleSelection.length>0){
        this.deleteAndAddShelfVisable=true;
      }else{
        this.deleteAndAddShelfVisable=false;
      }
    },
    doDeleteBranch(){
      this.$confirm('此操作将永久删除您选中的所有数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let jwt=localStorage.getItem("jwt");
        let selectGoods = this.multipleSelection;
        let ids=[];
        selectGoods.forEach(function(item){
          ids.push(item.id);
        });
        // console.log(ids);
        this.$axios
            .post('api/goods/goodsDelete',ids,{headers:{"jwt":jwt}})
            .then(response =>{
              if(response.data.code==200){
                this.$message.success("删除成功");
              }else if(response.data.data==406) {
                this.$message.warning(response.data.msg);
                this.$router.push("/login")
              }else {
                this.$message.error("删除失败");
              }
              this.queryGood();
            });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addGoods(){
      this.addAndUpdate.title="添加商品";
      this.rowData.id=''; //商品id
      this.rowData.goodName='';//商品名
      this.rowData.goodCode='';// 商品编号
      this.rowData.goodImg=''; //商品图片
      this.rowData.goodPrice=''; //商品单价
      this.rowData.marketPrice=''; //市场价格
      this.rowData.discount=''; //优惠价格
      this.rowData.typeId='';  //类型id
      this.rowData.createTime=''; //创建时间
      this.rowData.shelfStatus=0;//上架状态
      this.rowData.isPointGoods=0;
      this.rowData.repertory=1;
      this.addAndUpdateIsVisiable=true;
      this.isUpdate=false;
    },
    addAndUpdatesave(){
      let jwt=localStorage.getItem("jwt");
      if(this.isUpdate){
          this.$axios
              .post('api/goods/goodUpdate',this.rowData,{headers:{"jwt":jwt}})
              .then(response =>{
                if(response.data.code==200){
                  this.$message.success("修改成功");
                }else if(response.data.data==406) {
                  this.$message.warning(response.data.msg);
                  this.$router.push("/login")
                }else {
                  this.$message.error("修改失败");
                }
                this.queryGood();
                this.addAndUpdateIsVisiable=false;
              })
      }else{
        this.$axios
            .post('api/goods/goodAdd',this.rowData,{headers:{"jwt":jwt}})
            .then(response =>{
              if(response.data.code==200){
                this.$message.success("添加成功");
              }else if(response.data.data==406) {
                this.$message.warning(response.data.msg);
                this.$router.push("/login")
              }else {
                this.$message.error("添加失败");
              }
              this.queryGood();
              this.addAndUpdateIsVisiable=false;
            });
      }
    },
    nextPage(pageNo){
      this.pageGoodData.pageNum=pageNo;
    },
    prevPage(pageNo){
      this.pageGoodData.pageNum=pageNo;
    },
    currentPage(pageNo){
      this.pageGoodData.pageNum=pageNo;
      this.queryGood();
    },
    sizeChange(size){
      this.pageGoodData.pageSize=size;
      if (this.pageGoodData.pageNum!=1){
        this.pageGoodData.pageNum=1;
      }else{
        this.queryGood();
      }
    },
    doAddShelf(){
      this.$confirm('您选中的商品都将会上架, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let jwt=localStorage.getItem("jwt");
        let selectGoods = this.multipleSelection;
        let ids=[];
        selectGoods.forEach(function(item){
          ids.push(item.id);
        });
        // console.log(ids);
        this.$axios
            .post('api/goods/goodsAddShelf',ids,{headers:{"jwt":jwt}})
            .then(response =>{
              if(response.data.code==200){
                this.$message.success("上架成功");
              }else if(response.data.data==406) {
                this.$message.warning(response.data.msg);
                this.$router.push("/login")
              }else {
                this.$message.error("上架失败");
              }
              this.queryGood();
            });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消上架'
        });
      });
    },
    doDeleteShelf(){
      this.$confirm('您选中的商品都将会下架, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let jwt=localStorage.getItem("jwt");
        let selectGoods = this.multipleSelection;
        let ids=[];
        selectGoods.forEach(function(item){
          ids.push(item.id);
        });
        // console.log(ids);
        this.$axios
            .post('api/goods/goodsDeleteShelf',ids,{headers:{"jwt":jwt}})
            .then(response =>{
              if(response.data.code==200){
                this.$message.success("下架成功");
              }else if(response.data.data==406) {
                this.$message.warning(response.data.msg);
                this.$router.push("/login")
              }else {
                this.$message.error("下架失败");
              }
              this.queryGood();
            });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消下架'
        });
      });
    },
    handleAvatarSuccess(res, file) {
      this.rowData.goodImg="/api/file/"+res.data;
      // console.log(this.rowData.goodImg);
      // this.rowData.goodImg = URL.createObjectURL(file.raw);
      // console.log(this.rowData.goodImg);

    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isGIF = file.type === 'image/gif';

      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传头像图片只能是 JPG,GIF,PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    doQuit(){
      this.$axios
          .post("/api/common/quit",this.rowData,{headers:{'jwt':this.jwt}})
          .then(response =>{
            if(response.data.code==200){
              console.log(response.data.msg);
            }else if(response.data.data==406) {
              this.$message.warning(response.data.msg);
              this.$router.push("/login")
            }else {
              console.log(response.data.msg);
            }

          });
        this.addAndUpdateIsVisiable=false;
        this.$message.warning("成功取消"+this.addAndUpdate.title);
    }

  },
  created:function (){

    let jwt = localStorage.getItem("jwt");
    let account  = sessionStorage.getItem("account")
    this.$axios.get('api/users/queryJobIdByAccount?account='+account,
        {headers:{"jwt":jwt}})
        .then(response=>{
          console.log(response.data.data.jobId)
          if(response.data.code == 200 ){
            this.jobId = response.data.data.jobId
            this.queryGood();

          }else{

          }
        })


    this.jwt= localStorage.getItem("jwt");
    this.$axios.get("/api/type/queryList",{headers:{'jwt':this.jwt}})
        .then(response =>{
          if(response.data.code==200){
            this.goodType=response.data.data.list;
          }else if(response.data.data==406) {
            this.$message.warning(response.data.msg);
            this.$router.push("/login")
          }
        });
    // console.log(this.multipleSelection);
  }
}
</script>

<style scoped>
#pagehelper{
  margin-top: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>